//
//  HMOauthViewController.swift
//  WeiBo
//
//  Created by 李立达 on 15/12/7.
//  Copyright © 2015年 heima11. All rights reserved.
//
////App Key：3344270075
//
////App Secret：e0b61cae79f3d5aed4827acba7eac316
//
////   http://www.iteima.com
//
//
//
//
//
//class HMOAuthViewcontroller: UIViewController {
//    
//    
//    
//    func  loadAccessToken(code : String){
//        
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        
//        
//        
//        let params = [
//            
//            "client_id":"3344270075",
//            
//            "client_secret":"e0b61cae79f3d5aed4827acba7eac316",
//            
//            "grant_type" : "authorization_code",
//            
//            "code":code,
//            
//            "redirect_uri":"http://www.iteima.com/",
//            
//        ]
//        
//    }


import UIKit
import SVProgressHUD


class HMOauthViewController: UIViewController ,UIWebViewDelegate{

    lazy var webview : UIWebView = {
    
        let view = UIWebView()
    
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WEB_APPKEY)&redirect_uri=\(WEB_REDIRECT_URI)"
        
        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(URL: url!)
        
        webview.loadRequest(request)
        
        
    }
    
    
    private func setupUI()
    {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem( title: "取消", target: self, anction: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem ( title: "自动填充", target: self, anction: "autoFill")
        
        navigationItem.title = "微博登陆"
    }
    
    @objc private func cachel(){
    
    
    }
    
    override func loadView() {
        
        webview.delegate = self
        view = webview
        
    }
}

extension HMOauthViewController
{
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.URL?.absoluteString else{
            return true
        }
        if !url.hasPrefix(WEB_REDIRECT_URI){
            return true
        }
        
        if request.URL!.query!.hasPrefix("code=")
        {
        
        let code = request.URL!.query!.substringFromIndex("codo=".endIndex)
        print("\(code)")
        
        HMusercount.shareuserCount.loadAccessToken(code) { (isSucess) -> () in
            
            if !isSucess
            {
            print("登录失败")
                
                SVProgressHUD.showErrorWithStatus("网络异常登录失败")
            }
            else
            {
              print("登录成功")
                
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    // 2.跳到欢迎页
                    // 切换根控制器的逻辑,应该放在一起,一般放在 appdelegate 里面
                    NSNotificationCenter.defaultCenter().postNotificationName(HMSwitchRootVCNotifation, object: self)
                })
            }
        }
        }else{
            print(request.URL)
            dismiss()
        }
        return false
    }
    
    
    
    @objc private func autoFill(){
        print("autoFill")
        let jsString = "document.getElementById('userId').value='18612563240';document.getElementById('passwd').value='abcd8988705'"
        webview.stringByEvaluatingJavaScriptFromString(jsString)
    }

}

extension HMOauthViewController
{
    
  @objc private func dismiss(){
    
    SVProgressHUD.dismiss()
    dismissViewControllerAnimated(true, completion: nil)
    
    }

}

